package org.mysfit.ctp4j;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.mysfit.ctp4j.infra.utils.OSInfoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * 
 * @author long.gf
 *
 */
public class LoadLibrary {
	private static final Logger LOGGER = LoggerFactory.getLogger(LoadLibrary.class);
	
	public static final String LIBCTP = "libctp";
	
	public static void loadCtp(String version) throws IOException {
		if(StringUtils.isEmpty(version)) {
			throw new RuntimeException("version is empty!");
		}
		String tmp = LIBCTP.concat("_temp").concat(File.separator).concat(version);
		File tmpDir = new File(System.getProperty("java.io.tmpdir"), tmp);
		LOGGER.info("load lib to path:{}", tmpDir.getAbsolutePath());
        if (!tmpDir.exists()) {
            if (!tmpDir.mkdirs()) {
                throw new RuntimeException("create library temp dir failed!");
            }
        }
        FileUtils.cleanDirectory(tmpDir);
        if (OSInfoUtils.isWindows()) {
            loadLib(tmpDir, version, "thostmduserapi_se.dll");
            loadLib(tmpDir, version, "thosttraderapi_se.dll");
            loadLib(tmpDir, version, "thosttraderapi_wrap.dll");
		} else if (OSInfoUtils.isLinux()) {
            loadLib(tmpDir, version, "libthostmduserapi_se.so");
            loadLib(tmpDir, version, "libthosttraderapi_se.so");
            loadLib(tmpDir, version, "libthosttraderapi_wrap.so");
        } else {
        	LOGGER.warn("unsupported os");
        }
	}
	
	/**
     * load依赖
     *
     * @param directory 目录
     * @param version   版本号
     * @param libName   依赖名字
     * @throws IOException IO异常
     */
    private static void loadLib(File directory, String version, String libName) throws IOException {
    	String libPath = File.separator.concat("libctp")
    			.concat(File.separator).concat(version)
    			.concat(File.separator).concat(libName);
        FileUtils.copyInputStreamToFile(getResourceAsStream(libPath), new File(directory, libName));
        System.load(directory.getPath() + File.separator + libName);
    }
    
    private static InputStream getResourceAsStream(String resource) {
        final InputStream in = getContextClassLoader().getResourceAsStream(resource);
        return in == null ? LoadLibrary.class.getResourceAsStream(resource) : in;
    }

    private static ClassLoader getContextClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }
}
